﻿using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using EAF.Utility;
using App.Utility.ComEntity;

namespace App.Utility.FileHandle
{
    public static class FileSiteServer
    {
        #region ftp相关

        ///// <summary>
        ///// 上传方法
        ///// </summary>  
        ///// <param name="fileFrom">文件来源(前端:front 后端:back)</param>
        ///// <returns></returns>
        //public static JsonR Upload(HttpRequest Request, FileSource fileFrom = FileSource.Back)
        //{
        //    if (Request.HasFormContentType)
        //    {
        //        var fileList = Request.Form.Files;
        //        if (fileList != null)
        //        {
        //            if (fileList.Count > 0)
        //            {
        //                Stream stream = null;
        //                try
        //                {
        //                    var upFile = fileList.First();

        //                    //上传准入
        //                    var checkResult = FileAdmittance(upFile, fileFrom);
        //                    if (checkResult.JsonResult.code == 0)
        //                    {
        //                        var fileType = checkResult.FileType;
        //                        var binPath = Directory.GetCurrentDirectory();
        //                        var fileName = Guid.NewGuid().ToString().Replace("-", "") + upFile.FileName.Substring(upFile.FileName.LastIndexOf("."));
        //                        var filePath = checkResult.FileSaveDir + DateTime.Now.ToString("yyyyMMdd") + "/";

        //                        //获取流对象
        //                        stream = upFile.OpenReadStream();

        //                        switch (fileType.ToLower())
        //                        {
        //                            case "image": DoImage.SaveImage(binPath + filePath + fileName, stream); break;
        //                            case "excel": DoExcel.SaveExcel(binPath + filePath + fileName, stream); break;
        //                        }

        //                        //文件保存到本地,再分流处理是到移动到别的文件夹,还是移动到文件服务器
        //                        if (File.Exists(binPath + filePath + fileName))
        //                        {
        //                            var result = Upload2FileSite(binPath + filePath + fileName, filePath, fileName);
        //                            if (result.Result)
        //                            {
        //                                return new JsonR
        //                                {
        //                                    code = RespCode.OP_操作成功.GetHashCode(),
        //                                    message = "操作成功",
        //                                    body = result
        //                                };
        //                            }
        //                            else
        //                            {
        //                                return new JsonR
        //                                {
        //                                    code = RespCode.OP_操作失败.GetHashCode(),
        //                                    message = "操作失败",
        //                                    body = result
        //                                };
        //                            }
        //                        }
        //                        else
        //                        {
        //                            //Wathet.Log.Info("上传失败[" + upFile.FileName + "]", ComEnum.RabbitQueue.日志_常规);
        //                            throw new Exception("上传文件失败[" + upFile.FileName + "]");
        //                        }
        //                    }
        //                    else
        //                    {
        //                        return checkResult.JsonResult;
        //                    }

        //                }
        //                catch (Exception ex)
        //                {
        //                    throw new Exception("上传文件异常", ex);
        //                }
        //                finally
        //                {
        //                    if (stream != null)
        //                    {
        //                        stream.Close();
        //                        stream.Dispose();
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    return null;
        //}

        ///// <summary>
        ///// 文件从节点目录移动到图片站点文件夹下或者上传ftp
        ///// </summary>
        ///// <returns></returns>
        //public static UploadFileResult Upload2FileSite(string localFile, string filePath, string fileName)
        //{
        //    UploadFileResult result = new UploadFileResult();
        //    result.Result = false;
        //    if (File.Exists(localFile))
        //    {
        //        try
        //        {
        //            //进行分流(存储在同服务器文件夹/文件服务器) 
        //            var ftpSiteLocalPath = FileHandle.Config.FileSiteUpload_LocalPath;
        //            if (!string.IsNullOrEmpty(ftpSiteLocalPath))
        //            {
        //                //当配置是本地路径时(单节点运行), 文件移到
        //                result.Result = DoIOFile.Move(localFile, ftpSiteLocalPath + filePath + fileName);
        //            }
        //            else
        //            {
        //                var client = new DoFtps(FileHandle.Config.FileSiteUploadFtpAddressIp, FileHandle.Config.FileSiteUploadFtpUser, FileHandle.Config.FileSiteUploadFtpPassword, FileHandle.Config.FileSiteUploadFtpPort.ToInt());
        //                //配置了ftp之后,要上传到指定的文件服务器节点上
        //                result.Result = client.Upload(filePath + fileName, localFile);

        //                //client.DownLoad("远程路径例如: /upload/image/2019-03-02/lsjflsdjfl.png", Directory.GetCurrentDirectory() + "/upload/toFZ/lsjflsdjfl.png");
        //            }

        //            if (result.Result)
        //            {
        //                result.FileName = fileName;
        //                result.RelativePath = filePath + fileName;
        //                return result;
        //            }

        //        }
        //        catch (Exception ex)
        //        {
        //            //Wathet.Log.Error(ex.ToSimple(), ComEnum.RabbitQueue.日志_常规);
        //            throw new Exception("上传ftp异常", ex);
        //        }
        //        finally
        //        {
        //            //删除当前节点下的文件及文件夹
        //            DoIOFile.Delete(localFile, true);
        //        }
        //    }
        //    return result;

        //}

        ///// <summary>
        ///// 文件从文件站移动到本地
        ///// </summary>
        ///// <param name="localPath"></param>
        ///// <param name="filePath"></param>
        ///// <param name="fileName"></param>
        ///// <returns></returns>
        //public static string FileMove2Local(string localPath, string filePath, string fileName)
        //{
        //    try
        //    {
        //        //进行分流(存储在同服务器文件夹/文件服务器)
        //        var result = false;
        //        var localFullPath = Directory.GetCurrentDirectory() + localPath + fileName;
        //        var ftpSiteLocalPath = FileHandle.Config.FileSiteUpload_LocalPath;
        //        if (!string.IsNullOrEmpty(ftpSiteLocalPath))
        //        {
        //            //当配置是本地路径时(单节点运行), 文件移到
        //            result = DoIOFile.Move(ftpSiteLocalPath + filePath + fileName, localFullPath);
        //        }
        //        else
        //        {
        //            var client = new DoFtps(FileHandle.Config.FileSiteUploadFtpAddressIp, FileHandle.Config.FileSiteUploadFtpUser, FileHandle.Config.FileSiteUploadFtpPassword, FileHandle.Config.FileSiteUploadFtpPort.ToInt());

        //            //配置了ftp之后,从文件服务器节点上下载文件到本地
        //            //client.DownLoad("远程路径例如: /upload/image/2019-03-02/lsjflsdjfl.png", Directory.GetCurrentDirectory() + "/upload/toFZ/lsjflsdjfl.png");
        //            result = client.DownLoad(filePath + fileName, localFullPath);

        //        }

        //        if (result) { return localFullPath; }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("文件从文件站移动到本地", ex);
        //    }

        //    return null;
        //}

        #endregion

        /// <summary>
        /// 文件上传准入 只验证类型和大小
        /// </summary>
        /// <param name="reqFile">请求文件</param>
        /// <param name="fromType"></param>
        /// <returns></returns>
        public static FileAdmittanceResult Admittance(this IFormFile reqFile, FileSource fromType = FileSource.Back)
        {
            return FileAdmittance(reqFile, fromType);
        }

        /// <summary>
        /// 文件上传准入 只验证类型和大小
        /// </summary>
        /// <param name="reqFile">文件请求</param> 
        /// <param name="fromType">文件来源</param>
        /// <returns></returns>
        public static FileAdmittanceResult FileAdmittance(IFormFile reqFile, FileSource fromType = FileSource.Back)
        {
            int limitSize;
            string typeName;
            string fileSaveDir;
            var currFileSize = reqFile.Length;
            var fileInfo = new FileInfo(reqFile.FileName);
            var fileType = fileInfo.Extension.Replace(" ", "").ToLower().Replace(".", "");
            var allowImgType = FileHandle.Config.FileInfoImgType.ToLower().Split(",");
            var allowExcelType = FileHandle.Config.FileInfoExcelType.ToLower().Split(",");
            var allowVideoType = FileHandle.Config.FileInfoVideoType.ToLower().Split(",");
            FileAdmittanceResult result;

            if (allowImgType.Contains(fileType))
            {
                typeName = "image";
                fileSaveDir = Config.FileSiteUploadImagePath;
                //图片类型
                if (fromType == FileSource.Back)
                {
                    limitSize = FileHandle.Config.FileInfoAdminImgSize;
                }
                else
                {
                    limitSize = FileHandle.Config.FileInfoFrontImgSize;
                }
            }
            else if (allowExcelType.Contains(fileType))
            {
                typeName = "excel";
                fileSaveDir = Config.FileSiteUploadExcelPath;
                //excel类型
                if (fromType == FileSource.Back)
                {
                    limitSize = FileHandle.Config.FileInfoAdminExcelSize;
                }
                else
                {
                    //前台只允许传图片
                    result = new FileAdmittanceResult
                    {
                        JsonResult = new JsonR
                        {
                            code = RespCode.OP_操作失败.GetHashCode(),
                            message = "不支持excel类型文件"
                        },
                        FileType = typeName,
                        FileSaveDir = fileType
                    };
                    return result;
                }
            }
            else if (allowVideoType.Contains(fileType))
            {
                typeName = "video";
                fileSaveDir = Config.FileSiteUploadVideoPath;
                //video类型
                if (fromType == FileSource.Back)
                {
                    limitSize = FileHandle.Config.FileInfoAdminVideoSize;
                }
                else
                {
                    //前台暂时不允许传视频
                    result = new FileAdmittanceResult
                    {
                        JsonResult = new JsonR
                        {
                            code = RespCode.OP_操作失败.GetHashCode(),
                            message = "不支持video类型文件"
                        },
                        FileType = typeName,
                        FileSaveDir = fileType
                    };
                    return result;
                }
            }
            else
            {
                result = new FileAdmittanceResult
                {
                    JsonResult = new JsonR
                    {
                        code = RespCode.OP_操作失败.GetHashCode(),
                        message = "上传的类型不支持，请上传" + allowImgType.ToList().ToSplitStr(",") + "," + allowExcelType.ToList().ToSplitStr(",") + "类型文件！"
                    }
                };
                return result;
            }

            //尺寸判断
            if (currFileSize > limitSize * 1024)
            {
                result = new FileAdmittanceResult
                {
                    JsonResult = new JsonR
                    {
                        code = RespCode.OP_操作失败.GetHashCode(),
                        message = $"文件大小超过{DoString.GetSpaceSizeStr(limitSize * 1024)}限制"
                    },
                    FileSaveDir = fileSaveDir,
                    FileType = typeName
                };
                return result;
            }
            else
            {
                result = new FileAdmittanceResult
                {
                    JsonResult = new JsonR
                    {
                        code = RespCode.OP_操作成功.GetHashCode(),
                        message = "操作成功"
                    },
                    FileSaveDir = fileSaveDir,
                    FileType = typeName,
                    ExtName = fileType
                };
                return result;
            }
        }

        /// <summary>
        /// 保存excel文件流对象 文件已存在会删除
        /// </summary>
        /// <returns></returns>
        public static bool SaveFile(string fileUrl, Stream stream)
        {
            fileUrl = DoPath.GetFullPath(fileUrl);
            var file = new FileInfo(fileUrl);
            if (!file.Directory.Exists)
            {
                file.Directory.Create();
            }
            if (file.Exists)
            {
                file.Delete();
            }
            if (stream != null)
            {
                byte[] Buf = new Byte[stream.Length];
                stream.Read(Buf, 0, Buf.Length);
                stream.Seek(0, SeekOrigin.Begin);
                using (FileStream fs = new FileStream(fileUrl, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(Buf, 0, Buf.Length);
                    fs.Close();
                }
                return true;
            }
            return false;
        }
    }

    public class UploadFileResult
    {
        /// <summary>
        /// 文件id
        /// </summary>
        public int fId { get; set; }
        /// <summary>
        /// 操作结果 
        /// </summary>
        public bool Result { get; set; }
        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 文件完整路径
        /// </summary>
        public string FullUrl { get; set; }
        /// <summary>
        /// 文件相对路径
        /// </summary>
        public string RelativePath { get; set; }
    }

    public class FileAdmittanceResult
    {
        /// <summary>
        /// 响应结果
        /// </summary>
        public JsonR JsonResult { get; set; }
        /// <summary>
        /// 文件类型 image,excel,image,video,audio
        /// </summary>
        public string FileType { get; set; }
        /// <summary>
        /// 扩展名
        /// </summary>
        public string ExtName { get; set; }
        /// <summary>
        /// 系统配置的存放路径
        /// </summary>
        public string FileSaveDir { get; set; }

    }

    public enum FileSource
    {
        /// <summary>
        /// 来自后台
        /// </summary>
        Back = 1,
        /// <summary>
        /// 来自前端
        /// </summary>
        Front = 2,
    }

}
